#include "Contours.h"
#include "../utils/Logger.h"

Contours::Contours(Effects *effects) :
        effects(effects)
{
}

Contours::~Contours() {
    if (effects)
        delete effects;
}

IplImage* Contours::apply(const IplImage* in) {
    Log << "Applying contours effect." << endl;

    IplImage *tmp = (IplImage*) in;
    if (NULL != effects && effects->any()) {
        tmp = effects->apply(in);
    }
    if (1 != tmp->nChannels) {
        IplImage *tmp2 = grayEffect.apply(tmp);
        if (in != tmp)
            cvReleaseImage(&tmp);
        tmp = tmp2;
    }

    CvMemStorage* storage = cvCreateMemStorage();
    CvSeq* contours = NULL;
    cvFindContours(tmp, storage, &contours);

    cvReleaseImage(&tmp);

    IplImage *out = cvCreateImage(cvSize(in->width, in->height), in->depth, in->nChannels);
    cvCopy(in, out);
    cvDrawContours(out, contours, CV_RGB(255, 0, 0), CV_RGB(0, 255, 0), 1, CV_FILLED);

    return out;
}
